package co.th.helper.dao;

import java.math.BigDecimal;
import java.util.List;

import co.th.helper.jdbc.JdbcTemplate;
import co.th.helper.jdbc.mapper.TransactionLogRowMapper;
import co.th.helper.model.Person;
import co.th.helper.model.TransactionLog;

public class TransactionLogDAO extends JdbcTemplate<TransactionLog>{
	
	public List<Person> save(List<Person> listPerson) throws Exception{
		for(Person person : listPerson){
			this.save(person);
		}
		return listPerson;
	}
	
	public synchronized Person save(Person person) throws Exception{
		try {
			person.setPersonCode(genPersonCode());
			
			final String sql = "INSERT INTO person (person_code,person_title,person_first_name," +
					"person_last_name,person_type,telephone,email,imp_code,rp_code,remark,create_by," +
					"create_date,update_by,update_date) " +
					" VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
			Object[] params = new Object[14];
			params[0] = person.getPersonCode();
			params[1] = person.getPersonTitle();
			params[2] = person.getPersonFirstName();
			params[3] = person.getPersonLastName();
			params[4] = person.getPersonType();
			params[5] = person.getTelephone();
			params[6] = person.getEmail();
			params[7] = person.getImp();
			params[8] = person.getRp();
			params[9] = person.getRemark();
			params[10] = person.getCreateBy();
			params[11] = person.getCreateDate();
			params[12] = person.getUpdateBy();
			params[13] = person.getUpdateDate();
			
			int rowOfProcess = this.saveUnique(sql, params);
			if (rowOfProcess < 1){
				throw new Exception("Can't save person.");
			}
			return person;
		} catch (Exception ex) {
			throw ex;
		}
	}
	
	private BigDecimal genPersonCode() throws Exception{
		final String sql = "select max(person_code) AS person_code from person";
		TransactionLog objRow = queryUnique(sql, null, new TransactionLogRowMapper());
		return BigDecimal.valueOf(objRow.getTransaction().intValue() + 1);
	}
}
